<template>
  <div class="user-form">
    <a-form
      ref="formRef"
      :model="form"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
      label-align="right"
    >
      <a-form-item
        field="username"
        label="用户账号"
        :rules="[{ required: true, message: '请输入用户账号' }]"
      >
        <a-input
          v-model="form.username"
          placeholder="请输入用户账号"
          allow-clear
          :disabled="isEdit"
        />
      </a-form-item>
      
      <a-form-item
        v-if="!isEdit"
        field="password"
        label="密码"
        :rules="[{ required: !isEdit, message: '请输入密码' }]"
      >
        <a-input-password
          v-model="form.password"
          placeholder="请输入密码"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="nickName"
        label="用户昵称"
      >
        <a-input
          v-model="form.nickName"
          placeholder="请输入用户昵称"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="realName"
        label="真实姓名"
      >
        <a-input
          v-model="form.realName"
          placeholder="请输入真实姓名"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="mobile"
        label="手机号码"
      >
        <a-input
          v-model="form.mobile"
          placeholder="请输入手机号码"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="gender"
        label="用户性别"
      >
        <a-radio-group v-model="form.gender">
          <a-radio :value="UserGenderEnum.MALE">男</a-radio>
          <a-radio :value="UserGenderEnum.FEMALE">女</a-radio>
          <a-radio :value="UserGenderEnum.UNKNOWN">未知</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item
        field="status"
        label="帐号状态"
      >
        <a-radio-group v-model="form.status">
          <a-radio :value="UserStatusEnum.ENABLED">正常</a-radio>
          <a-radio :value="UserStatusEnum.DISABLED">停用</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item
        field="remark"
        label="备注"
      >
        <a-textarea
          v-model="form.remark"
          placeholder="请输入备注"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
      
      <a-divider>角色分配</a-divider>
      
      <a-form-item field="roleIds" label="用户角色">
        <a-select
          v-model="form.roleIds"
          placeholder="请选择用户角色"
          multiple
          allow-clear
        >
          <a-option v-for="role in roleOptions" :key="role.id" :value="role.id">
            {{ role.roleName }}
          </a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { createUser, updateUser, User, UserGenderEnum, UserStatusEnum } from '@/api/system/user';
import { getRoleList } from '@/api/system/role';

// 接收父组件传递的属性
const props = defineProps({
  formData: {
    type: Object as () => Partial<User>,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

// 表单引用
const formRef = ref();

// 表单数据
const form = reactive<User>({
  id: undefined,
  username: '',
  password: '',
  nickName: '',
  realName: '',
  avatar: '',
  mobile: '',
  gender: UserGenderEnum.UNKNOWN,
  status: UserStatusEnum.ENABLED,
  remark: '',
  roleIds: []
});

// 角色选项
const roleOptions = ref<any[]>([]);

// 监听formData变化，更新表单数据
watch(
  () => props.formData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      Object.assign(form, newVal);
    }
  },
  { immediate: true, deep: true }
);

// 验证表单
const validate = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((errors: any) => {
      if (errors) {
        console.log('表单验证失败:', errors);
        resolve(false);
      } else {
        console.log('表单验证通过');
        resolve(true);
      }
    });
  });
};

// 提交表单
const submit = async () => {
  try {
    const submitData = { ...form };
    
    if (props.isEdit) {
      // 编辑用户
      await updateUser(submitData);
      Message.success('更新用户成功');
    } else {
      // 创建用户
      await createUser(submitData);
      Message.success('创建用户成功');
    }
    return true;
  } catch (error) {
    console.error(props.isEdit ? '更新用户失败:' : '创建用户失败:', error);
    Message.error(props.isEdit ? '更新用户失败' : '创建用户失败');
    return false;
  }
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  Object.assign(form, {
    id: undefined,
    username: '',
    password: '',
    nickName: '',
    realName: '',
    avatar: '',
    mobile: '',
    gender: UserGenderEnum.UNKNOWN,
    status: UserStatusEnum.ENABLED,
    remark: '',
    roleIds: []
  });
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await getRoleList({ current: 1, size: 100 });
    roleOptions.value = res.data.records || [];
  } catch (error) {
    console.error('获取角色列表失败:', error);
    Message.error('获取角色列表失败');
  }
};

// 组件挂载时获取角色列表
onMounted(() => {
  fetchRoleList();
});

// 暴露方法给父组件
defineExpose({
  validate,
  submit,
  resetForm
});
</script>

<style scoped lang="less">
.user-form {
  padding: 16px 0;
}
</style> 